package com.LeeCode;

import java.util.ArrayList;
import java.util.List;

/**
 * 给表达式添加运算符
 */

public class Code282 {
    public static void main(String[] args) {
        String num = "123";
        int target = 6;
        System.out.println(new Code282().addOperators(num, target));

    }

    public List<String> addOperators(String num, int target) {
        List<String> result = new ArrayList<>();
        if (num == null || num.length() == 0) return result;

        backtrack(num, target, 0, 0, 0, new StringBuilder(), result);
        return result;
    }

    private void backtrack(String num, int target, int start, long currentSum,
                           long prevNum, StringBuilder expression, List<String> result) {
        if (start == num.length()) {
            if (currentSum == target) {
                result.add(expression.toString());
            }
            return;
        }

        for (int i = start; i < num.length(); i++) {
            // 处理前导零
            if (i > start && num.charAt(start) == '0') break;

            long currentNum = Long.parseLong(num.substring(start, i + 1));
            int len = expression.length();

            if (start == 0) {
                // 第一个数字
                backtrack(num, target, i + 1, currentNum, currentNum,
                        expression.append(currentNum), result);
                expression.setLength(len);
            } else {
                // 加法
                backtrack(num, target, i + 1, currentSum + currentNum, currentNum,
                        expression.append("+").append(currentNum), result);
                expression.setLength(len);

                // 减法
                backtrack(num, target, i + 1, currentSum - currentNum, -currentNum,
                        expression.append("-").append(currentNum), result);
                expression.setLength(len);

                // 乘法
                backtrack(num, target, i + 1,
                        currentSum - prevNum + prevNum * currentNum,
                        prevNum * currentNum,
                        expression.append("*").append(currentNum), result);
                expression.setLength(len);
            }
        }
    }
}
